<template>
  <!--  机台物料关系 -->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" :rules="formRules" ref="searchForm" class="demo-form-inline">
        <el-form-item label="机台">
          <el-select v-model="searchParam.equipmentId" placeholder="请选择机台" clearable filterable remote
                     reserve-keyword
                     :remote-method="remoteEquipment" style="width: 200px">
            <el-option v-for="item in equipmentOptions" :key="item.id" :label="item.equipmentCode"
                       :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
              v-model="searchParam.date"
              type="date"
              placeholder="请选择日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="物料">
          <el-select v-model="searchParam.materialid" placeholder="请选择物料" remote
                     :remote-method="getMaterialSearchList" filterable style="width: 200px"
          >
            <el-option v-for="item of materialSearchList" :key="item.id" :label="item.materialNo"
                       :value="item.id">
              <span style="float: left">{{ item.materialNo }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="submitForm()">查询</el-button>
          <el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button  type="primary"  :icon="Plus" @click="handleAdd()">新建</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 320px)">
        <el-table-column label="序号" align="center" width="70" fixed>
          <template #default="scope"> {{ (pageSearch.current - 1) * pageSearch.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="equipmentCode" label="机台" align="center" min-width="200" show-overflow-tooltip/>
        <el-table-column prop="materialNo" label="物料" align="center" min-width="200"/>
        <el-table-column prop="createTime" label="时间段" align="center" min-width="200">
          <template #default="scope"> {{ scope.row.startDateTime }} - {{ scope.row.endDateTime }}</template>
        </el-table-column>
        <el-table-column prop="userNickname" label="人员" align="center" min-width="200"/>

      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current" v-model:page-size="pageSearch.pageSize"
                       :page-sizes="[10, 20, 50, 100, 200, 500]" layout="total, sizes, prev, pager, next"
                       :total="pageTotal"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </div>

    <el-dialog v-model="showCrud" title="新建" width="1100">
      <el-form :model="formData" label-width="100px" ref="ruleFormRef">
        <el-row>
          <el-form-item label="工厂/车间">
            <el-tree-select v-model="formData.organizationId" :data="workshopOptions" check-strictly
                            :render-after-expand="false"
                            :props="{
          									children: 'children',
          									label: 'orgName',
          									value: 'id',
          								}" @change="organizationIdChange" style="width: 200px"/>
          </el-form-item>
          <el-form-item label="机台">
            <el-select v-model="formData.equipmentId" placeholder="请选择机台" clearable filterable remote
                       style="width: 200px">
              <el-option v-for="item in equipmentFormOptions" :key="item.id" :label="item.equipmentCode"
                         :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="班次">
<!--            @change="handleShiftChange"-->
            <el-select v-model="formData.shiftId" placeholder="请选择班次" style="width: 200px">
              <el-option label="早班" :value="1"/>
              <el-option label="晚班" :value="2"/>
            </el-select>
          </el-form-item>
        </el-row>
        <!--          <el-col :span="24">-->
        <!--            <el-form-item label="点巡检内容">-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <el-row v-for="(item, index) in formData.inspectionItemJson" :key="index">
          <div style="display: flex;width: 100%;align-items: center;margin: 0 20px 10px 0">
            {{ index + 1 }} .
            <el-date-picker
                v-model="item.times"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="margin: 0 20px"
            />
            <!--            endDateTime结束 startDateTime开始时间-->
            <el-select v-model="item.materialid" placeholder="请选择物料" filterable  remote
                       :remote-method="getMaterialList"
                       style="width: 200px;margin-right: 20px"
            >
              <el-option v-for="items of materialList" :key="items.id" :label="items.materialNo"
                         :value="items.id">
                <span style="float: left">{{ items.materialNo }}</span>
              </el-option>
            </el-select>
            <!--            materialList find出materialNo materialName-->
            <el-select v-model="item.userId" placeholder="请选择人员" filterable style="width: 200px"
            >
              <el-option v-for="items of teamPeopleData" :key="items.id" :label="items.nickname"
                         :value="items.id"/>
            </el-select>
            <!--            循环teamPeopleData find出userNickname username-->
            <el-button type="text" @click="addInput" style="margin-left: 10px"
                       :icon="Plus" v-if="index === 0">新建
            </el-button>
            <el-button type="text" @click="removeInput(index)" style="margin-left: 10px; color: red; "
                       :icon="Delete" v-if="index !== 0">删除
            </el-button>
          </div>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script lang="ts" setup>
import {ref, onMounted} from 'vue';
import {lineAll} from '@/api/baseData/productionLine';
import {ElMessage, ElForm} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Plus, Refresh, Search} from '@element-plus/icons-vue';
import dayjs from 'dayjs';

onMounted(() => {
  getList();
  getOption();
});

const searchForm = ref<InstanceType<typeof ElForm>>();
const workshopOptions = ref([]);
const pageSearch = ref({
  current: 1,
  pageSize: 10
});

const dicData = ref([
  {label: "新建", value: 0},
  {label: "待排产", value: 1},
  {label: "已排产", value: 2},
  {label: "下发", value: 3},
  {label: "开工", value: 4},
  {label: "中断", value: 5},
  {label: "暂停", value: 6},
  {label: "完成", value: 7},
]);

const materialList = ref([]);
const materialSearchList = ref([]);


const pageTotal = ref(null); // 页面总数
const searchParam = ref({
  // times: [
  //   dayjs().subtract(1, 'month').format('YYYY-MM-DD HH:mm:ss'),
  //   dayjs().format('YYYY-MM-DD HH:mm:ss')
  // ],
});

const handleAdd = () => {
  equipmentFormOptions.value = []
  formData.value = {
    shift: 'day', // 默认白班
    inspectionItemJson: [{}]
  };
  showCrud.value = true

}

const handleSave = () => {
  const param = []
  for (const items of formData.value.inspectionItemJson) {
    param.push({
      equipmentId: formData.value.equipmentId,
      equipmentCode: equipmentFormOptions.value.find(item => item.id === formData.value.equipmentId).equipmentCode,
      equipmentName: equipmentFormOptions.value.find(item => item.id === formData.value.equipmentId).equipmentName,
      materialId: items.materialid,
      materialName: materialList.value.find(item => item.id === items.materialid).materialName,
      materialNo: materialList.value.find(item => item.id === items.materialid).materialNo,
      userId: items.userId,
      userNickname: teamPeopleData.value.find(item => item.id === items.userId).nickname,
      username: teamPeopleData.value.find(item => item.id === items.userId).username,
      startDateTime: items.times[0],
      endDateTime: items.times[1],
      shiftId  :formData.value.shiftId
    })
  }
  axiosInstance.post('/api/equipmentProductionMaterialHistory/saveBatch', param)
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        ElMessage.success('保存成功');
        showCrud.value = false;
        getList();
      });
}

const paginatedData = ref([]);
const workRoomList = ref([]); // 车间
const equipmentData = ref([]);
const equipmentOptions = ref([])
const equipmentFormOptions = ref([])

const showCrud = ref(false)
const formData = ref({inspectionItemJson: [{}]})

const addInput = () => {
  formData.value.inspectionItemJson.push({content: ''});
};

const removeInput = (index) => {
  formData.value.inspectionItemJson.splice(index, 1);
};

const formRules = ref({
  organizationId: [{required: true, message: '请选择工厂/车间', trigger: 'change'}],
  equipmentIds: [{required: true, message: '请选择设备', trigger: 'change'}]
});

const organizationIdChange = (e) => {
  formData.value.equipmentId = null
  axiosInstance.post('/api/basedataEquipment/getPage', {
    current: 1,
    pageSize: 99999,
    organizationId: e
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        equipmentFormOptions.value = res.data.records;
      });
}

const handleShiftChange = (newShift: string) => {
  formData.value.inspectionItemJson.forEach(item => {
    if (item.date) {
      const dateObj = dayjs(item.date);
      const baseDate = dateObj.format('YYYY-MM-DD');

      // 保留原日期，仅修改时间部分
      const newTime = newShift === 'day'
          ? `${baseDate} 08:00:00`
          : `${baseDate} 20:00:00`;

      item.date = dayjs(newTime).format('YYYY-MM-DD HH:mm:ss');
    } else {
      // 初始化带有时分秒的完整时间
      const baseDate = dayjs().format('YYYY-MM-DD');
      const newTime = newShift === 'day'
          ? `${baseDate} 08:00:00`
          : `${baseDate} 20:00:00`;

      item.date = newTime;
    }
  });
};

// 时间选择范围限制
const getPickerOptions = (shift: string) => ({
  disabledDate(time: Date) {
    return false; // 不限制日期选择
  },
  selectableRange: shift === 'day'
      ? ['08:00:00 - 20:00:00']
      : ['20:00:00 - 23:59:59', '00:00:00 - 08:00:00']
});

const remoteEquipment = (value) => {
  if (!value) {
    return
  }
  axiosInstance.post('/api/basedataEquipment/getPage', {
    current: 1,
    pageSize: 50,
    equipmentCode: value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        equipmentOptions.value = res.data.records;
      });
}

const getMaterialList = (e) => {
  if (e) {
    axiosInstance.post('/api/basedata/material/getPage', {
      current: 1,
      pageSize: 20,
      materialName: e
    }).then(res => {
      materialList.value = res.data.records
    })
  }
}

const getMaterialSearchList = (e) => {
  if (e) {
    axiosInstance.post('/api/basedata/material/getPage', {
      current: 1,
      pageSize: 20,
      materialName: e
    }).then(res => {
      materialSearchList.value = res.data.records
    })
  }
}

//
// const getMaterialList = (e) => {
//   if (e) {
//     axiosInstance.post('/api/basedata/material/getPage', {
//       current: 1,
//       pageSize: 20,
//       materialName: e
//     }).then(res => {
//       materialList.value = res.data.records
//     })
//   }
// }
//


const buildTree = (items) => {
  const itemMap = {};
  const rootItems = [];
  items.forEach((item) => {
    itemMap[item.id] = {...item, name: item.orgName, children: []};
  });
  items.forEach((item) => {
    if (!item.parentId || item.parentId === '0') {
      rootItems.push(itemMap[item.id]);
    } else {
      if (itemMap[item.parentId]) {
        itemMap[item.parentId].children.push(itemMap[item.id]);
      }
    }
  });

  return rootItems;
};


const teamPeopleData = ref([]);//班组人员

const getOption = () => {
  lineAll({current: 1, pageSize: 100000}).then(res => {
    if (res.code === 200) {
      const list = buildTree(res.data.records.map((item) => {
        return {
          ...item.extension,
          ...item
        };
      }));
      workshopOptions.value = list[0].children;
    }
  });
  axiosInstance.post('/api/basedata/material/getPage', {
    current: 1,
    pageSize: 20,
  }).then(res => {
    materialList.value = res.data.records
    materialSearchList.value = res.data.records
  })
  axiosInstance.post('/api/basedataUser/getPage', {
    current: 1,
    pageSize: 999999,
  }).then(res => {
    teamPeopleData.value = res.data.records
  })
  axiosInstance.post('/api/basedataEquipment/getPage', {
    current: 1,
    pageSize: 50
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        equipmentOptions.value = res.data.records;
      });
  // axiosInstance.post('/api/basedataOrganization/getAll', {})
  //     .then(res => {
  //       if (res.code !== 200) {
  //         ElMessage.error(res.message);
  //         return false;
  //       }
  //       workRoomList.value = res.data;
  //     });
};


const getList = () => {
  axiosInstance.post('/api/equipmentProductionMaterialHistory/getPage', {
    ...searchParam.value,
    startDate: searchParam.value?.times?.[0],
    endDate: searchParam.value?.times?.[1],
    times: undefined,
    ...pageSearch.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records;
        pageTotal.value = res.data.total;
      });
};


const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};


const submitForm = () => {
  searchForm.value.validate((valid) => {
    if (valid) {
      getList();
    } else {
      ElMessage.error('请检查表单输入');
      return false;
    }
  });
};


const resetSearch = () => {
  pageSearch.value.current = 1;
  searchForm.value.clearValidate();
  searchParam.value = {
    times: [
      dayjs().subtract(1, 'month').format('YYYY-MM-DD HH:mm:ss'),
      dayjs().format('YYYY-MM-DD HH:mm:ss')
    ]
  };
  submitForm()
};
</script>
<style scoped></style>